<template>
  <view @click="closeList">
    <l-background has-sub-background />

    <template v-if="audit">
      <view id="tab" class="padding-top-30 padding-lr-30 padding-bottom-14">
        <l-notice-bar :type="noticeType" :list="noticeList" />
      </view>

      <scroll-view :style="{height:height+'px'}" scroll-y>
        <view class="padding-lr-30 padding-bottom-30">
          <view class="margin-bottom-14 card">
            <new-image-model :auditCv="auditCv" :data="form" :list="documentsList" :show="editShow" :must="audit" :disabled="!(status != 1 && status != 2)" @update="update" @showExampleImage="showExampleImage" />
          </view>

          <view class="margin-bottom-14">
            <basic-info-model ref="basicInfo" :data="form" :show="editShow" :car-id="carId" :status="status" :audit="audit" :type-id="carInfo.typeId" :driver-name="driverName" @update="update" />
          </view>

          <view class="margin-bottom-14 card">
            <identity-info-model :data="form" :must="audit" :disabled="status == 1 || status == 2" :status="status" @update="update" @changeDate="changeDate" />
          </view>

          <view class="margin-bottom-14 card">
            <transport-info-model :degree-label="degreeLabel" :data="form" :must="audit" @update="update" @changeDate="changeDate" @changeCarDegree="showAction=true" />
          </view>

          <view class="margin-bottom-14 card">
            <new-image-model :auditCv="auditCv" must :data="form" :list="insuranceList" @update="update" />
          </view>

          <view class="margin-bottom-14 card">
            <insurance-info-model :data="form" :must="audit" @update="update" @changeDate="changeDate" />
          </view>

          <view class="card">
            <vehicle-photos-model :data="form" :status="status" :car-pic="carPic" @update="update" />
          </view>
        </view>
      </scroll-view>
    </template>

    <template v-else>
      <view id="tab" class="padding-top-30 padding-lr-30">
        <l-tab-bar type="2" :tabs="tabList" :active-inx.sync="tabInx" />
      </view>

      <scroll-view v-show="tabInx===0" :style="{height:height+'px'}" scroll-y>
        <view class="padding-lr-30 padding-bottom-30">
          <view class="margin-bottom-14">
            <basic-info-model ref="basicInfo" :data="form" :show="editShow" :car-id="carId" :status="status" :audit="audit" :type-id="carInfo.typeId" :driver-name="driverName" @update="update" />
          </view>

          <view v-if="status !== 2" class="card">
            <vehicle-photos-model :data="form" :status="status" :car-pic="carPic" @update="update" />
          </view>
        </view>
      </scroll-view>

      <scroll-view v-show="tabInx===1" :style="{height:height+'px'}" scroll-y>
        <view v-show="tabInx===1" class="padding-lr-30 padding-bottom-30">
          <view v-if="editShow" class="margin-bottom-14">
            <new-image-model :auditCv="auditCv" :data="form" :list="documentsList" :show="editShow" :must="audit" :disabled="status == 1 || status == 2" @update="update" @showExampleImage="showExampleImage" />
          </view>

          <view class="margin-bottom-14 card" :style="{borderRadius:!editShow ? '0 0 14rpx 14rpx' :''}">
            <identity-info-model :data="form" :must="audit" :disabled="status == 1 || status == 2" :status="status" @update="update" @changeDate="changeDate" />
          </view>

          <view class="card">
            <transport-info-model :degree-label="degreeLabel" :data="form" :must="audit" :disabled="status == 1 || status == 2" @update="update" @changeDate="changeDate" @changeCarDegree="showAction=true" />
          </view>
        </view>
      </scroll-view>

      <scroll-view v-show="tabInx===2" :style="{height:height+'px'}" scroll-y>
        <view v-show="tabInx===2" class="padding-lr-30 padding-bottom-30">
          <view class="margin-bottom-14 box-radius-bottom">
            <new-image-model :auditCv="auditCv" :data="form" :list="insuranceList" @update="update" />
          </view>

          <view class="card">
            <insurance-info-model :data="form" :must="audit" @update="update" @changeDate="changeDate" />
          </view>
        </view>
      </scroll-view>
    </template>
    <safe-area-bottom id="safeBottom" />
    <l-bottom-button :text="buttonText" @click="submit" />

    <example-image :show.sync="exampleImageShow" :info="exampleImageInfo" />
    <tui-datetime ref="dateTime" :show-cancel="false" :type="dateType" :end-year="2100" :set-date-time="setDateTime" @confirm="setDate" />
    <tui-actionsheet :show.sync="showAction" :item-list="itemList" @click="change" />
  </view>
</template>

<script>
import BasicInfoModel from '../components/basic-info-model/basic-info-model'
import VehiclePhotosModel from '../components/vehicle-photos-model/vehicle-photos-model'
import IdentityInfoModel from '../components/identity-info-model/identity-info-model'
import TransportInfoModel from '../components/transport-info-model/transport-info-model'
import InsuranceInfoModel from '../components/insurance-info-model/insurance-info-model'
import ImageModel from './components/image-model/image-model.vue'
import { mapGetters, mapMutations } from 'vuex'
import { dateFormat, formVerify, loading ,numberTypeCheck} from '@/common/util'
import { carDegreeList, examineStatus } from '../index'
import { getCarDetail, addCarInfo, updateCarInfo, submitReviewCar } from '../api'
import { name } from '@/common/config'
export default {
  name: 'AddVehicle',
  components: {
    BasicInfoModel,
	ImageModel,
    VehiclePhotosModel,
    IdentityInfoModel,
    TransportInfoModel,
    InsuranceInfoModel
  },
  data() {
    return {
	  auditCv:false,
      loading: null,
      showAction: false,
      degreeLabel: '',
      height: 0,
      dateType: 2,
      setDateTime: '',
      set: '',
      m: 'bizExp,vlicenceDxp',
      tabInx: 0,
      tabList: [
        { title: '基本信息' },
        { title: '证件信息' },
        { title: '保险信息' }
      ],
      form: {
        userId: '',
        typeId: '',
        number: '',
        driverId: '',
        seatAmount: '',
        bizScopeId: [],
        brand: '',
        photo: '',
        vlicencePicture: '',
        frameNumber: '',
        engineNumber: '',
        brandModel: '',
        useType: '',
        vlicenceRegister: '',
        bizPicture: '',
        fuelType: '',
        autoClass: '',
        bizDate: '',
        bizExp: '',
        vlicenceDxp: '',
        compulsoryInsPic: '',
        compulsoryInsExp: '',
        carrierInsPic: '',
        carrierInsExp: '',
        commerceInsPic: '',
        commerceInsExp: '',
        remark: ''
      },
      carInfo: {
        typeId: ''
      },
      carId: '',
      carPic: [],
      status: 0,
      audit: false,
      driverName: '',
      insuranceList: [
        { attr: 'compulsoryInsPic', label: '交强险保险单', default: 'https://tbb-file.oss-cn-shenzhen.aliyuncs.com/tbb_admin_app/static/baoxian.png' },
        { attr: 'carrierInsPic', label: '承运人险保险单', default: 'https://tbb-file.oss-cn-shenzhen.aliyuncs.com/tbb_admin_app/static/baoxian.png' },
        { attr: 'commerceInsPic', label: '商业险保险单', default: 'https://tbb-file.oss-cn-shenzhen.aliyuncs.com/tbb_admin_app/static/baoxian.png' }
      ],
      documentsList: [
        { attr: 'vlicencePicture', label: '行驶证', default: 'https://tbb-file.oss-cn-shenzhen.aliyuncs.com/tbb-portal/static/singshizheng.png', example: 'true' },
        { attr: 'bizPicture', label: '道路运输证', default: 'https://tbb-file.oss-cn-shenzhen.aliyuncs.com/tbb-portal/static/zigezheng.png', example: 'true' }
      ],
      exampleImageInfo: '',
      exampleImageShow: false
    }
  },
  computed: {
    // 编辑时是否展示
    editShow() {
      if (examineStatus) return this.audit || !this.carInfo || !this.carInfo.examineStatus || [examineStatus.REVIEWING, examineStatus.REVIEW_NOT_PASS].indexOf(this.carInfo.examineStatus) >= 0
      else return true
    },
    buttonText() {
      if (this.audit) return '提交审核'
      else return this.carId ? '确定' : '添加车辆'
    },
    noticeList() {
      if (this.audit) {
        const list = []
        if (this.carInfo.vlicenceExamineStatus === examineStatus.REVIEW_NOT_PASS) {
          list.push(`行驶证审核未通过: ${this.carInfo.vlicenceExamineReason || ''}`)
        }
        if (this.carInfo.bizExamineStatus === examineStatus.REVIEW_NOT_PASS) {
          list.push(`道路运输证审核未通过: ${this.carInfo.bizExamineReason || ''}`)
        }
        return list.length ? list : [`根据${name}旅游客运平台规定，上架的车辆必须完善相关信息`]
      }
      return []
    },
    noticeType() {
      if (examineStatus) return this.carInfo && this.carInfo.examineStatus == examineStatus.REVIEW_NOT_PASS ? 'danger' : 'error'
      else return 'error'
    },
    itemList() {
      return carDegreeList.map(item => {
        return {
          text: item.label,
          value: item.value,
          zIndex: 'secondary'
        }
      })
    },
    validationList() {
      if (this.audit) {
        return [
          { attr: 'vlicencePicture', toast: '请上传行驶证' },
          { attr: 'bizPicture', toast: '请上传道路运输证' },
          { attr: 'brand', toast: '请选择车型' },
          { attr: 'seatAmount', toast: '请输入核定载人数' },
          { attr: 'number', toast: '请输入车牌号' },
          { attr: 'brandModel', toast: '请输入品牌型号' },
          { attr: 'useType', toast: '请输入使用性质' },
          { attr: 'frameNumber', toast: '请输入车辆识别代码' },
          { attr: 'engineNumber', toast: '请输入发动机号' },
          { attr: 'fuelType', toast: '请选择燃油类型' },
          { attr: 'vlicenceRegister', toast: '请选择行驶证注册时间' },
          { attr: 'vlicenceDxp', toast: '请选择行驶证年检时间' },
          { attr: 'autoClass', toast: '请选择档次' },
          { attr: 'bizDate', toast: '请选择运输证发证日期' },
          { attr: 'bizExp', toast: '请选择运输证年检时间' },
          { attr: 'compulsoryInsPic', toast: '请选择交强险保险单' },
          { attr: 'carrierInsPic', toast: '请选择承运人险保险单' },
          { attr: 'compulsoryInsExp', toast: '请选择交强险到期时间' },
          { attr: 'carrierInsExp', toast: '请选择承运人险到期时间' }
        ]
      } else {
        return [
          { attr: 'brand', toast: '请选择车型' },
          { attr: 'seatAmount', toast: '请输入核定载人数' },
          { attr: 'number', toast: '请输入车牌号' }
        ]
      }
    },
    ...mapGetters({
      chooseDriverInfo: 'chooseDriverInfo',
      userId: 'userId'
    })
  },
  onLoad(options) {
	  console.log(options);
    this.carId = options.id
    if (options.id) {
      this.audit = options.type === 'audit'
      if (this.audit) this.insuranceList.pop()
      uni.setNavigationBarTitle({
        title: this.audit ? '资料审核' : '编辑车辆'
      })
      this.getCarInfo()
	 this.auditCv =  this.audit 
	 // this.audit  ? this.auditCv = false : this.auditCv = true
    }
  },
  onShow() {
    this.setDriver()
  },
  mounted() {
    this.getHeight()
  },
  methods: {
    getHeight() {
      const wHeight = this.sysInfo().windowHeight
      this.getElementInfo('#tab', res => {
        this.height = wHeight - res.height - this.px()
        this.getElementInfo('#safeBottom', res => {
          this.height -= res.height
        })
      })
    },
	imgFile(data){ //证件照数据过滤
		let dataArr = ['vlicencePicture','bizPicture','compulsoryInsPic','carrierInsPic','commerceInsPic'] 
		let arr = ['tbb_admin_app/static/baoxian.png','tbb-portal/static/singshizheng.png','tbb-portal/static/zigezheng.png']
		for(let value of dataArr){
			let arrData = this.form[value] != '' ? this.form[value].split(",") : ''
			if(arrData != '' && arrData.length > 0){
				for(let j = 0 ;j <= arrData.length - 1 ; j++){
					for(let i = 0 ; i <= arr.length - 1 ;i++){
						if(arrData[j] && arrData[j] != ''){
							if(arrData[j].indexOf(arr[i]) >= 0){
								arrData.splice(j,1)
							}
						}
					}
				}
			}
			this.form[value] = arrData != '' ? arrData.join(",") : ''
		}
	},
    update(e) {
      this.form = Object.assign(this.form, e)
    },
    // 提交表单
    async submit() {
	  this.imgFile(this.form)
	  if(!numberTypeCheck(this.form.seatAmount,'核定载人数请输入数字类型')){
		  return false
	  }
	  
      if (formVerify(this.form, this.validationList)) {
        const data = this.copyData(this.form)
		if(data.engineNumber && data.engineNumber.length != 20) {
			this.toast("请输入20位发动机号！")
			return
		}
        data.userId = this.userId
        let msg
        let err
        let res
        this.loading = loading('提交中')
        if (this.audit && !this.checkDate()) return false
        if (this.audit) {
          // 提交审核
          [err, res] = await this.auditVehicle(data)
          msg = '提交审核成功'
        } else if (this.carId) {
          // 修改车辆
          [err, res] = await updateCarInfo(this.carId, data)
          msg = '修改成功'
        } else {
			
          // 新增车辆
          [err, res] = await addCarInfo(data)
          msg = '添加成功'
        }
        this.loading.hide()
        if (!this.$http.errorCheck(err, res)) return false

        this.toast(msg, () => {
          this.jump()
        })
      }
    },
    // 验证证件是否到期
    checkDate() {
      const data = this.copyData(this.form)
      const vlicenceExp = new Date(data.vlicenceDxp.replace(/-/g, '/'))
      if (data.vlicenceRegister) {
        // 如果有发证日期，到期时间为：到期时间的“年和月” + 发证日期的“日”
        const vlicenceDate = new Date(data.vlicenceRegister.replace(/-/g, '/'))
        vlicenceExp.setDate(vlicenceDate.getDate())
      }
      if (!this.compare(vlicenceExp.getTime())) {
        this.toast('行驶证年检时期已到期，不符合上路标准')
        return false
      }

      const bizExp = new Date(data.bizExp.replace(/-/g, '/'))
      if (data.bizDate) {
        // 如果有发证日期，到期时间为：到期时间的“年和月” + 发证日期的“日”
        const bizDate = new Date(data.bizDate.replace(/-/g, '/'))
        bizExp.setDate(bizDate.getDate())
      }
      if (!this.compare(bizExp.getTime())) {
        this.toast('道路运输证年检时期已到期，不符合上路标准')
        return false
      }
      if (!this.compare(data.compulsoryInsExp)) {
        this.toast('交强险已到期，不符合上路标准')
        return false
      }
      if (!this.compare(data.carrierInsExp)) {
        this.toast('承运人险已到期，不符合上路标准')
        return false
      }
      return true
    },
    compare(date2) {
      const date = typeof date2 === 'number' ? date2 : date2.replace(/-/g, '/')
      const dates1 = new Date().getTime()
      const dates2 = new Date(date).getTime()
      if (dates1 <= dates2) {
        return true
      } else {
        return false
      }
    },
    // 获取车辆相关详情
    async getCarInfo() {
      const [err, res] = await getCarDetail(this.carId)
      if (!this.$http.errorCheck(err, res)) return false
      const data = res.data.data
      this.carInfo = data
      this.driverName = data.driverNickName
      this.status = data.examineStatus
      if (this.carInfo.photo) {
        this.carPic = this.carInfo.photo.split(',')
      }
      this.form.vlicenceDxp = data.vlicenceExp
      Object.keys(this.form).forEach(key => {
        if (data[key]) this.form[key] = data[key]
      })
      this.form.fuelType = data.fuelType
      carDegreeList.forEach(item => {
        if (item.value === this.form.autoClass) this.degreeLabel = item.label
      })
    },
    // 提交审核
    async auditVehicle(data) {
      const [err, res] = await updateCarInfo(this.carId, data)
      if (!this.$http.errorCheck(err, res)) {
        this.loading.hide()
        return false
      }

      return await submitReviewCar(Object.assign(data, {
        id: this.carId,
        vlicenceExp: data.vlicenceDxp
      }))
    },
    // 显示示例图
    showExampleImage(e) {
      this.exampleImageInfo = e.attr
      this.exampleImageShow = true
    },
    // 修改日期
    changeDate(attr) {
      if (this.m.includes(attr)) this.dateType = 3
      else this.dateType = 2

      this.setDateTime = this.form[attr] || dateFormat()

      if (this.set !== attr) this.$refs.dateTime.initData()

      this.set = attr
      this.$refs.dateTime.show()
    },
    // 确认修改的日期
    setDate(e) {
      if (e) {
        this.form[this.set] = this.m.includes(this.set) ? e.result + '-01' : e.result
      }
    },
    // 设置司机
    setDriver() {
      if (this.chooseDriverInfo) {
        this.form.driverId = this.chooseDriverInfo.driverIdSelect
        this.driverName = this.chooseDriverInfo.driverNameSelect
        this.setChooseDriverInfo(null)
      }
    },
    // 修改汽车档次
    change(e) {
      this.showAction = false
      this.form.autoClass = e.value
      this.degreeLabel = e.text
    },
    closeList() {
      this.$refs.basicInfo.showCarModel = false
    },
    ...mapMutations({
      setChooseDriverInfo: 'order/setChooseDriverInfo'
    })
  }
}
</script>

<style scoped lang="scss">
@include setPadding(bottom,14);

</style>
